package br.com.controller.filtros;

import java.io.IOException;
import java.net.URL;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import br.com.controller.Login;
import br.com.model.Permissao;

/**
 * Servlet Filter implementation class FiltroLogin
 */

public class Filtro implements Filter {

	public void goToUrl(String destino, HttpServletRequest req,
			HttpServletResponse res) {

		try {
			URL url = new URL("http", req.getServerName(), req.getServerPort(),
					"/web/" + destino);
			// System.out.println(" redirecionado para URL->"+url.toString());
			res.sendRedirect(url.toString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * Default constructor.
	 */
	public Filtro() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException,
			ServletException {

		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		HttpSession session = req.getSession();

		Login login = (Login) session.getAttribute("login");

		if (login != null) {
			// pega o id da permissao do usuario
			int permissao = login.getUsuario().getPermissao().getIdPermissao();
			//pega a permissao requerida para acessar a pagina requisitada pelo usuario
			int permissaoRequerida = (int) request.getAttribute("permissaoRequerida");
			
			// compara permissao do usuario com a permissao requerida para
			// acessar a pagina solicitada
			if (permissao == permissaoRequerida)
				chain.doFilter(request, response);
			else {
				switch (permissao) {
				case Permissao.ADMIN:
					goToUrl("view/admin/inicio.xhtml", req, res);
					break;
				case Permissao.PROFESSOR:
					goToUrl("view/professor/inicio.xhtml", req, res);
					break;
				case Permissao.ALUNO:
					goToUrl("view/aluno/inicio.xhtml", req, res);
					break;
				default:
					goToUrl("index.xhtml", req, res);
					break;
				}
			}
		} else{
			//inicia um login de visitante
			session.setAttribute("login", new Login());
			goToUrl("index.xhtml", req, res);
		}
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
